<template>
  <a-modal
    title="操作"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item
          label="账号"
          :labelCol="{span: 4}"
          :wrapperCol="{span: 20}"
        >
          <a-input v-decorator="['loginName', {rules: [{required: true, message: '请输入账号！'}]}]" />
        </a-form-item>
        <a-form-item
          label="昵称"
          :labelCol="{span: 4}"
          :wrapperCol="{span: 20}"
        >
          <a-input v-decorator="['name', {rules: [{required: false}]}]" />
        </a-form-item>
        <!-- <a-form-item
           label="人员"
           :labelCol="{span: 4}"
           :wrapperCol="{span: 20}"
         >
         
           <person ref="cu" :v-model.sync="cu"
           v-decorator="['openid', {rules: [{required: true, message: '请选择人员！'}]}]" 
           ></person>
         </a-form-item> -->
        <template v-if="!visiblePasword">
          <a-form-item
            label="密码"
            :labelCol="{span: 4}"
            :wrapperCol="{span: 20}"
          >
            <a-input
              v-decorator="[
                'password',
                {
                  rules: [
                    {
                      required: true,
                      message: '请输入密码',
                    },
                    {
                      validator: validateToNextPassword,
                    },
                  ],
                },
              ]"
              type="password"
            />
           
          </a-form-item>
          <a-form-item
            label="确认密码"
            :labelCol="{span: 4}"
            :wrapperCol="{span: 20}"
          >
            <a-input
              v-decorator="[
                'confirm',
                {
                  rules: [
                    {
                      required: true,
                      message: '请确认密码!',
                    },
                    {
                      validator: compareToFirstPassword,
                    },
                  ],
                },
              ]"
              type="password"
              @blur="handleConfirmBlur"
            />
          </a-form-item>
        </template>
        <a-form-item v-bind="formItemLayoutWithOutLabel" v-if="visiblePasword">
          <a-button type="dashed" style="width: 100%" @click="editPassword">
            <a-icon type="edit" /> 修改密码
          </a-button>
        </a-form-item>

        </a-form-item>
        <a-form-item
          label="选择角色"
          :labelCol="{span: 4}"
          :wrapperCol="{span: 20}"
        >
          <div v-if="treeData && treeData.length">
            <template>
              <a-tree
                checkable
                :defaultExpandAll="true"
                :tree-data="treeData"
                :checked-keys="checkedKeys"
                @check="onCheck"
             
              />
            </template>
          </div>
        </a-form-item>
       
      </a-form>
    </a-spin>
  </a-modal>
</template>


<script>
import { getPermissions } from '@/api/manage'
import pick from 'lodash.pick'
  import person from '../../myComponent/Person'

import { Tree } from 'ant-design-vue'
  import {
    postAxiosUrl,
    getUrl
  } from '@/api/manage'
export default {
  components:{ ATree  :Tree,
    person },
  data () {
    return {
      id : '',
      visible: false,
      visiblePasword: false,
      confirmLoading: false,
      confirmDirty: false,
      form: this.$form.createForm(this),
      formItemLayoutWithOutLabel: {
        wrapperCol: {
          xs: { span: 24, offset: 0 },
          sm: { span: 20, offset: 4 },
        },
      },
      cu: [],
      cuId : '',
      treeData : [],
      expandedKeys :[],
      checkedKeys  :[],
    }
  },
  created () {
     this.fetch()
  },
  methods: {
  add () {
    this.id = ''
    this.form.resetFields()
    this.visible = true
    this.visiblePasword = false
    this.checkedKeys = []
    // this.$refs.cu.setDefault(null)
  },
  edit (record) {
    console.log(record)
    this.form.resetFields()
     const { form: { setFieldsValue } } = this
     this.visible = true
     this.visiblePasword = true
     const me = this
      this.$nextTick(() => {
        me.id = record.id
        setFieldsValue(pick(record, ['loginName']))
        setFieldsValue(pick(record, ['name']))
         setFieldsValue(pick(record, ['userType']))
        // this.$refs.cu.setDefault(record.openid, record.address)
         me.fetchPermission()
        
    })
  },
  editPassword (record) {
      this.visiblePasword = false
  },
  close () {
      this.$emit('close')
      this.visible = false
  },
  handleCancel () {
      this.close()
  },
  fetch(params = {}) {
    console.log('params:', params)
    this.loading = true
    var _this = this
    return getUrl('getAllRole4User', Object.assign(params, this.queryParam))
      .then(data => {
       
        this.treeData = data.result
        this.expandedKeys = [0]
        
      })
  },
  fetchPermission() {
    this.loading = true
    var _this = this
    return getUrl('getRole4user', {id : _this.id})
      .then(data => {
        _this.checkedKeys = data.result
       
      })
  },
  handleConfirmBlur(e) {
        const value = e.target.value
        this.confirmDirty = this.confirmDirty || !!value
      },
  compareToFirstPassword(rule, value, callback) {
    const form = this.form
    if (value && value !== form.getFieldValue('password')) {
      callback('两次密码不一致')
    } else {
      callback()
    }
  },
  validateToNextPassword(rule, value, callback) {
    const form = this.form
    if (value && this.confirmDirty) {
      form.validateFields(['confirm'], { force: true })
    }
    callback()
  },
  handleOk () {
      const _this = this
      
      // 触发表单验证
      this.form.validateFields((err, values) => {
        // 验证表单没错误
        if (!err) {
          console.log('form values', values)

          _this.confirmLoading = true
         values.id = this.id
         values.roles = this.checkedKeys
         postAxiosUrl('saveUser', values)
           .then(data => {
             if(!data.success){
               _this.$message.warning(data.error)
               _this.confirmLoading = false
             }else{
               _this.visible = false
               _this.confirmLoading = false
               _this.$emit('ok', values)
             }

           })
        }else{}
      })
    },
    onExpand(expandedKeys) {
      console.log('onExpand', expandedKeys)
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys
    },
    onCheck(checkedKeys, obj) {
      this.checkedKeys = checkedKeys
    },

  }
}
</script>

<style>
</style>
